package sf.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;

import sf.jsonloader.JsonLoader;
import sf.model.Context;
import sf.model.DBColumnInfo;
import sf.model.SQLTableModel;

public class Browser extends JPanel {

	private static final long serialVersionUID = 1L;

	private StandardForm parentForm;
	private Context context;

	private JScrollPane scrollPane;
	private JTable table;
	private SQLTableModel model;
	private TableRowSorter<SQLTableModel> rowSorter;

	private JLabel overlay;

	public Browser(StandardForm parentForm, Context context) {
		this.parentForm = parentForm;
		this.context = context;

		init();
		
		if ((context.getMode() & StandardForm.MODE_SEARCH) != 0)
			showSearchOverlay(true);
	}

	private void init() {
		setLayout(new BorderLayout());

		model = new SQLTableModel(context, parentForm.getStatusBar());
		rowSorter = new TableRowSorter<SQLTableModel>(model);
		table = new JTable(model);
		table.setRowSorter(rowSorter);

		table.setPreferredScrollableViewportSize(new Dimension(600, 200));

		table.getTableHeader().setReorderingAllowed(false);
		table.getTableHeader().setResizingAllowed(false);
		table.getTableHeader().setFont(table.getTableHeader().getFont().deriveFont(Font.BOLD));

		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.setShowVerticalLines(false);
		table.setIntercellSpacing(new Dimension(0, 1));
		//table.setRequestFocusEnabled(false);
		table.setSelectionBackground(new Color(255, 223, 166));
		table.setSelectionForeground(Color.black);

		table.setDefaultRenderer(Timestamp.class, new DefaultTableCellRenderer() {
			private static final long serialVersionUID = 1L;
			private SimpleDateFormat formatter;

			@Override
			protected void setValue(Object value) {
				if (formatter == null)
					formatter = new SimpleDateFormat("dd.MM.yyyy");
				setText((value == null) ? "" : formatter.format(value));
			}
		});
		
		//table.setAutoCreateRowSorter(true);

		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				if (parentForm.getMode() != StandardForm.MODE_ADD)
					parentForm.getController().processRowSelectionChanged(e);

				// boolean rowSelected = table.getSelectedRow() != -1;
				// firePropertyChange("rowSelected", !rowSelected, rowSelected);
			}
		});
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				parentForm.getController().processTableClick(e);
			}
		});

		packTableColumns();

		scrollPane = new JScrollPane(table);

		add(scrollPane, BorderLayout.CENTER);

		createSearchLogo();

		add(overlay, BorderLayout.WEST);
	}

	public void packTableColumns() {
		TableColumnModel columnModel = table.getColumnModel();
		for (int i = 0; i < columnModel.getColumnCount(); i++) {
			int width = model.getColumnSize(i);
			if (width < 8)
				width *= 10;
			else
				width *= 6;
			columnModel.getColumn(i).setPreferredWidth(width);
		}
	}

	private void createSearchLogo() {
		overlay = new JLabel();
		overlay.setIcon(new ImageIcon(getClass().getResource("img/search_big.png")));
		overlay.setText("<html>Unesite kriterijume za pretragu baze.<br>Tabela: <b>" + JsonLoader.getInstance().get(context.getTable().toUpperCase(), "name") + "</b></html>");
		overlay.setVisible(false);
	}

	public void selectFirstRow() {
		int rowCount = table.getModel().getRowCount();
		if (rowCount > 0)
			table.changeSelection(0, 0, false, false);
	}

	public void selectLastRow() {
		int rowCount = table.getModel().getRowCount();
		if (table.getRowSorter() != null)
			rowCount = rowSorter.getViewRowCount();
		
		if (rowCount > 0)
			table.changeSelection(rowCount - 1, 0, false, false);
	}

	public int getSelectedRow() {
		int selectedRow = table.getSelectedRow();
		return (selectedRow != -1) ? table.convertRowIndexToModel(selectedRow) : -1;
	}

	public void setSelectedRow(int index) {
		int rowCount = table.getModel().getRowCount();
		if (table.getRowSorter() != null)
			rowCount = rowSorter.getViewRowCount();
		
		if (rowCount > 0 && index < rowCount)
			table.changeSelection(index, 0, false, false);
	}

	public JTable getTable() {
		return table;
	}

	public String getTableName() {
		return context.getTable();
	}

	public void refreshTable() {
		model.refresh();
		packTableColumns();
	}

	public void showSearchOverlay(boolean visible) {
		scrollPane.setVisible(!visible);
		overlay.setVisible(visible);
	}

	public List<DBColumnInfo> getTableColumns() {
		return model.getColumns();
	}
	
	public TableRowSorter<SQLTableModel> getTableRowSorter() {
		return rowSorter;
	}
}
